package com.sanctuary.tools;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sanctuary.interfaces.Model;
import com.sanctuary.interfaces.ObjectSerializer;
import com.thoughtworks.xstream.XStream;

public class XStreamSerializer implements ObjectSerializer {
	private static XStream xstream = null;
	private static final Log LOG = LogFactory.getLog(XStreamSerializer.class);

	public Object toObject(String in) {
		if (xstream == null) init();
		return xstream.fromXML(in);
	}

	public String toString(Object in) {
		if (xstream == null) init();
		return xstream.toXML(in);
	}

	private static void init() {
		xstream = new XStream();
		List<String> aliases = BaseTool.CONFIG_BEAN.getXstreamAliases();
		try {
			for (String alias : aliases) {
				Model m = (Model) Class.forName(alias).newInstance();
				xstream.alias(m.getAliasName(), m.getClass());
			}
		} catch (Exception ex) {
			LOG.warn(ex);
		}
	}

}
